package com.zky.gulimall.ware.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zky.common.utils.R;
import com.zky.gulimall.ware.feign.MemberFeignService;
import com.zky.gulimall.ware.vo.FareVo;
import com.zky.gulimall.ware.vo.MemberAddressVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zky.common.utils.PageUtils;
import com.zky.common.utils.Query;
import com.zky.gulimall.ware.dao.WareInfoDao;
import com.zky.gulimall.ware.entity.WareInfoEntity;
import com.zky.gulimall.ware.service.WareInfoService;


@Service("wareInfoService")
@Slf4j
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {
    @Autowired
    private MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareInfoEntity> queryWrapper = new QueryWrapper<>();
        Object key = params.get("key");
        if (Objects.nonNull(key)) {
            String key1 = (String) key;
            queryWrapper.and(e -> {
                e.eq("id", key1).or().like("name", key1).or().like("address", key1).or().like("areacode", key1);
            });
        }
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public FareVo getFare(Long addrId) {
        R info = memberFeignService.info(addrId);
        FareVo fareVo = new FareVo();
        if (info.isSuccess()) {
            String data = JSON.toJSONString(info.get("memberReceiveAddress"));
            MemberAddressVo addressVo = JSON.parseObject(data, new TypeReference<MemberAddressVo>() {
            });
            log.warn("addressVo:" + addressVo);
            if (addressVo != null) {
                //暂时无复杂联动信息，给一个模拟的运费
               // int num = (int) (Math.random() * 1000);
                //暂时写死
                int num=100;
                log.warn("num:" + num);
                fareVo.setFare(new BigDecimal(num));
                fareVo.setAddress(addressVo);
            }
        }
        log.warn("addressVo:" + fareVo);
        return fareVo;
    }

}